<?php

// 应用公共文件
/**
 *
 * @method token生成
 * @version
 * @User: bevan
 * @return token
 */
function cmf_create_token()
{
    $token = md5(uniqid()) . time() . md5(uniqid());
    return md5($token);
}

/**
 *
 * @method 加密用户密码
 * @version
 * @User: bevan
 * @param $user_pass 明文密码
 * @return 加密后的用户密码
 */
function cmf_crypt_password($user_pass)
{
    return md5($user_pass . cmf_crypt_salt());
}

/**
 *
 * @method  密码比较
 * @version
 * @User: bevan
 * @param $password 未加密的明文
 * @param $passwordInDb 在数据库中加密的密码
 * @return  布尔 比较结果
 */
function cmf_compare_password($password, $passwordInDb)
{
    if (cmf_crypt_password($password) == $passwordInDb) {
        return true;
    } else {
        return false;
    }
}

/**
 *
 * @method 获取inge_cmf 加密盐值
 * @version
 * @User: bevan
 * @return 盐值
 */
//TODO:修改为配置项
function cmf_crypt_salt()
{
    return 'abc%^.&123#@!CMF_';
}

/**
 *
 * @method 获取当前请求用户的token
 * @version
 * @return token
 */
function cmf_get_token()
{
    $token = \thans\auth\facade\Token::instance();
    return $token->getToken();
}

/**
 *
 * @method 获取当前请求用户的uid
 * @version
 * @return token
 */
function cmf_get_uid()
{
    $token = \thans\auth\facade\Token::instance();
    return $token->uid;
}

/**
 *
 * @method 判断用户是否登录
 * @version
 * @User: thans
 * @return boolean
 */
function cmf_is_login()
{
    $token = \thans\auth\facade\Token::instance();
    $res = $token->isLogin();
    if ($res) {
        return ['code' => 1001, 'msg' => 'success', 'data' => $res];
    } else {
        return ['code' => 4001, 'msg' => '请先登录', 'data' => []];
    }
}

function cmf_auth_check($name)
{
    $token = \thans\auth\facade\Token::instance();
    $auth = \thans\auth\facade\Auth::instance();
    $res = $auth->check($name, $token->uid);
    return $res;
}

function html_cmf_auth_check($name)
{
    if (cmf_auth_check($name)) {
        echo '';
    } else {
        echo 'display:none;';
    }
}

/**
 *
 * @method 获取请求用户的设备详情
 * @version
 * @User: bevan
 * @return
 */
function cmf_get_user_agent()
{
    return request()->header('User-Agent') ?: '';
}

/**
 *
 * @method 获取当前用户的登录设备
 * @version
 * @User: bevan
 * @return device_type
 */
function cmf_get_user_device()
{

    return request()->header('IG-Device-Type') ?: cookie('IG-Device-Type') ?: 'web';
}

function cmf_get_device_type()
{
    $agent = new Jenssegers\Agent\Agent();
    if ($agent->isMobile() && !$agent->isTablet()) {
        if ($agent->isiOS()) {
            return 'ios';
        } elseif ($agent->isAndroidOS()) {
            // Android系统
            return 'android';
        } elseif ($agent->isWindowsPhoneOS()) {
            //WindowsPhone系统
            return 'windows phone';
        } else {
            return $agent->platform();
        }

    } elseif ($agent->isTablet()) {
        if ($agent->isiOS()) {
            return 'ipad';
        } else {
            return 'pad';
        }
    }
    $platform = $agent->platform();
    return $platform == 'OS X' ? 'mac' : $platform;
}

/**
 * 判断是否为微信访问
 * @return boolean
 */
function cmf_is_wechat()
{
    $detect = new Detection\MobileDetect();
    if ($detect->isWeChat()) {
        return true;
    }
    return false;
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function cmf_random_string($len = 6)
{
    $chars = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9",
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars); // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

/**
 *
 * @method 是否匹配手机号码
 * @version
 * @User: bevan
 * @param $mobile
 * @return bool
 */
function cmf_validate_mobile($mobile)
{
    return preg_match('/^1[34578]{1}\d{9}$/', $mobile, $match);
}

/**
 *
 * @method 是否匹配邮箱
 * @version
 * @User: bevan
 * @param $email
 * @return bool
 */
function cmf_validate_email($email)
{
    return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', $email, $match);
}

/**
 *
 * @method 清空系统缓存
 * @version
 * @User: bevan
 * @return
 */
function cmf_clear_cache()
{
    $runtime = BASE_ROOT . 'runtime/';
    $res = cmf_sub_dirs('../runtime');
    foreach ($res as $val) {
        $files = cmf_scan_dir($runtime . '/' . $val . "/*");
        foreach ($files as $file) {
            @unlink($runtime . '/' . $val . '/' . $file);
        }
        @rmdir($runtime . '/' . $val);
    }
    \think\facade\Cache::clear();
    return true;
}

/**
 * 去除字符串中的指定字符
 * @param string $str 待处理字符串
 * @param string $chars 需去掉的特殊字符
 * @return string
 */
function cmf_strip_chars($str, $chars = '?<*.>\'\"')
{
    return preg_replace('/[' . $chars . ']/is', '', $str);
}

/**
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 * @param $pattern
 * @return array
 */
function cmf_scan_dir($pattern, $flags = null)
{
    $files = glob($pattern, $flags);
    if (empty($files)) {
        $files = [];
    } else {
        $files = array_map('basename', $files);
    }

    return $files;
}

/**
 * 获取某个目录下所有子目录 不用绝对目录，目录是相对于public目录
 * @param $dir
 * @return array
 */
function cmf_sub_dirs($dir)
{
    $dir = ltrim($dir, "/");
    $dirs = [];
    $subDirs = cmf_scan_dir("$dir/*", GLOB_ONLYDIR);
    if (!empty($subDirs)) {
        foreach ($subDirs as $subDir) {
            $subDir = "$dir/$subDir";
            array_push($dirs, $subDir);
            $subDirSubDirs = cmf_sub_dirs($subDir);
            if (!empty($subDirSubDirs)) {
                $dirs = array_merge($dirs, $subDirSubDirs);
            }
        }
    }
    return $dirs;
}

/**
 *
 * @method 秒转 分
 * @version
 * @User: bevan
 * @param $seconds
 * @return 分钟
 */
function cmf_second_to_minute($seconds)
{
    return floor($seconds / 60);
}

function cmf_check_primary_key_is_number($id)
{
    if (!is_numeric($id)) {
        return ['code' => 4001, 'msg' => '参数错误', 'data' => []];
    }
}

function cmf_option($type = '', $key = '', $val = '')
{
    if ($val) {
        $res = \app\admin\facade\Options::set($type, $key, $val);
        return $res;
    }
    $res = \app\admin\facade\Options::read($type, $key);
    if ($res['code'] == '1001') {
        return $key ? $res['data'][$key] : $res['data'];
    } else {
        return '';
    }
}

function cmf_auto_option()
{
    $res = \app\admin\facade\Options::auto();
    if ($res['code'] == '1001') {
        return $res['data'];
    } else {
        return '';
    }
}

function cmf_read_dir_queue($dir)
{
    $files = array();
    $queue = array($dir);
    while ($data = each($queue)) {
        $path = $data['value'];
        if (is_dir($path) && $handle = opendir($path)) {
            while ($file = readdir($handle)) {
                if ($file == '.' || $file == '..') {
                    continue;
                }

                $files[] = $real_path = $path . '/' . $file;
                if (is_dir($real_path)) {
                    $queue[] = $real_path;
                }

            }
        }
        closedir($handle);
    }
    return $files;
}

/**
 * 添加钩子
 * @param string $hook 钩子名称
 * @param mixed $params 传入参数
 * @param mixed $extra 额外参数
 * @return void
 */
function hook($hook, $params = null)
{
    return \think\facade\Hook::listen($hook, $params, false);
}

/**
 * 添加钩子,只执行一个
 * @param string $hook 钩子名称
 * @param mixed $params 传入参数
 * @param mixed $extra 额外参数
 * @return mixed
 */
function hook_one($hook, $params = null)
{
    return \think\facade\Hook::listen($hook, $params, true);
}


function cmf_get_language()
{
    $language = app\admin\facade\Language::getLanguage();
    return $language['data'];
}

function cmf_get_image_url($path)
{
    if ((strpos($path, 'http') === 0) || strpos($path, '/') === 0) {
        return $path;
    } else {
        $url = hook_one('get_image_url') ?: '';
        return $url . '/' . $path;
    }
}

//插件函数

function cmf_get_addons_class($name)
{
    $name = ucwords($name);
    $addonsDir = \think\Loader::parseName($name, 0, true);
    $name = \think\Loader::parseName($name, 1, true);
    $class = "addons\\{$addonsDir}\\{$name}";
    return $class;
}